package com.hisan.freeride.home.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.view.View;

import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.base.BaseFragment;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.callback.NoDialogCallback;
import com.hisan.freeride.common.utils.CacheUtils;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.GsonUtils;
import com.hisan.freeride.common.utils.PermissionsChecker;
import com.hisan.freeride.common.utils.utils.NotificationUtils;
import com.hisan.freeride.common.utils.utils.TokenUtils;
import com.hisan.freeride.common.view.AlertDialog;
import com.hisan.freeride.common.view.MyLinearLayoutManager;
import com.hisan.freeride.databinding.HomeBinding;
import com.hisan.freeride.home.activity.CartCertificationActivity;
import com.hisan.freeride.home.activity.DoingActivity;
import com.hisan.freeride.home.activity.Link_DetailsActivtity;
import com.hisan.freeride.home.activity.LoginActivity;
import com.hisan.freeride.home.activity.LoveCartActivity;
import com.hisan.freeride.home.activity.LoveCartDetailsActivity;
import com.hisan.freeride.home.activity.PushActivity;
import com.hisan.freeride.home.activity.RealNameActivity;
import com.hisan.freeride.home.activity.ReservationActivity;
import com.hisan.freeride.home.activity.RotationActivity;
import com.hisan.freeride.home.activity.Select_CityActivity;
import com.hisan.freeride.home.adapter.HomeAdapter;
import com.hisan.freeride.home.model.AdData;
import com.hisan.freeride.home.model.MyDriver;
import com.hisan.freeride.home.model.Realname;
import com.hisan.freeride.home.model.TList;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.lzy.okgo.OkGo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends BaseFragment<HomeBinding>  {
    private HomeAdapter adapter;
    private String city = "";
    private List<AdData> advertBeans;
    private List<String> iamges;

    //危险权限（运行时权限）
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.GET_ACCOUNTS,
            Manifest.permission.READ_SMS,
            Manifest.permission.VIBRATE
    };

    //防止页面重复初始化
    private boolean isup = true;
    private PermissionsChecker mPermissionsChecker;
    private static final int PERMISSION_REQUEST_CODE = 0;// 系统权限返回码
    private static final String PACKAGE_URL_SCHEME = "package:";
    private  boolean isRequireCheck=true;
    //分页加载
    private int page = 1;
    private  List<TList.DataBean> dataBeanlist=new ArrayList<>();

    private int type=1;
    public static HomeFragment getInstance() {
        HomeFragment homeFragment = null;
        if (homeFragment == null) {
            homeFragment = new HomeFragment();
        }
        return homeFragment;
    }

    protected int getLayoutId() {
        return R.layout.home;
    }

    protected void initView() {
        String city=CacheUtils.getInstance().getString("city");
        if (!CollectionUtils.isNullOrEmpty(city)){
            mBinding.site.setText(city);
        }
        Bundle bundle = getActivity().getIntent().getExtras();
        if (!CollectionUtils.isNullOrEmpty(bundle)) {
            city = bundle.getString("city");
            mBinding.site.setText(city);
        }
        mPermissionsChecker=new PermissionsChecker(getActivity());
        mBinding.setStateModel(mStateModel);
        mBinding.rv.setLayoutManager(new MyLinearLayoutManager(getActivity()));
        adapter = new HomeAdapter(getActivity(), new ArrayList<>(0));
        mBinding.rv.setAdapter(adapter);
        adapter.setButtonClickListener((p, data) -> {
            if (p == 0) {
                Bundle nbundle = new Bundle();
                nbundle.putInt("driver_id", data.getDriver_id());
                startActivityForResult(LoveCartDetailsActivity.class, 0, nbundle,true);
            } else if (p == 1) {
                if (!CollectionUtils.isNullOrEmpty(data)) {
                    if (BaseAppLication.getInstance().islogin()) {
                        Bundle sbundle = new Bundle();
                        sbundle.putInt("id", data.getId());
                        startActivityForResult(ReservationActivity.class, 0, sbundle,true);
                    } else {
                        startActivityForResult(LoginActivity.class, 99, null,false);
                    }
                }
            }
        });

    }

    @Override
    protected void initEvent() {
        mBinding.pager.setOnBannerItemClickListener(position -> {
            if (!CollectionUtils.isNullOrEmpty(advertBeans)) {
                switch (advertBeans.get(position).getLink_mode()){
                    case 0:
                            RotationActivity.skip(getActivity(), advertBeans.get(position).getLink_url());
                        break;
                    //活动
                    case 1:
                        break;
                    case 2:
                        if (!CollectionUtils.isNullOrEmpty(advertBeans.get(position).getLink_id())){
                            Bundle bundle=new Bundle();
                            bundle.putInt("id",advertBeans.get(position).getLink_id());
                            startActivityForResult(Link_DetailsActivtity.class, 99, bundle,false);
                        }
                        break;
                    //商品
                    case 3:
                        break;
                }
            }
        });
        mBinding.selectCity.setOnClickListener(v -> startActivityForResult(Select_CityActivity.class, 96, null,false));
        mBinding.realname.setOnClickListener(v -> {
            String  token= TokenUtils.getToken();
            if (!CollectionUtils.isNullOrEmpty(token)) {
                startActivityForResult(RealNameActivity.class, 96, null, true);
            } else {
                startActivityForResult(LoginActivity.class, 99, null,true);
            }
        });
        mBinding.loveCart.setOnClickListener(v -> startActivityForResult(LoveCartActivity.class, 98, null,true));
        mBinding.welfare.setOnClickListener(v -> startActivityForResult(DoingActivity.class, 98, null,true));
        mBinding.cart.setOnClickListener(v -> startActivityForResult(DoingActivity.class, 98, null,true));
        mBinding.push.setOnClickListener(v -> {
            String  token= TokenUtils.getToken();
            if (!CollectionUtils.isNullOrEmpty(token)) {
                getRealname();
            } else {
                startActivityForResult(LoginActivity.class, 99, null,true);
            }
        });
        mBinding.pull.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                page=1;
                dataBeanlist.clear();
                mBinding.pull.finishRefresh();
                getTrip();
            }
            @Override
            public void loadMore() {
                page++;
                mBinding.pull.finishLoadMore();
                getTrip();
            }
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {
        String token=TokenUtils.getToken();
        page=1;
        if (!CollectionUtils.isNullOrEmpty(token)&&BaseAppLication.getInstance().islogin()){
            if (BaseAppLication.getInstance().getIs_realname()==0){
                getname();
            }
        }else {
            mBinding.ranliner.setVisibility(View.GONE);
        }

        dataBeanlist.clear();
        OkGo.<List<Object>>get(AppConfig.indexData)
                .tag(this)
                .params("model", 1)
                .execute(new NoDialogCallback<List<Object>>(getActivity()) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<Object>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())) {
                            advertBeans=new ArrayList<>();
                            iamges=new ArrayList<>();
                            if (!CollectionUtils.isNullOrEmpty(response.body())){
                                JSONArray jsonArray=new JSONArray(response.body());
                                for (int i=0;i<jsonArray.length();i++){
                                    try {
                                        JSONObject json=jsonArray.getJSONObject(i);
                                        AdData adData=new AdData();
                                        iamges.add(json.getString("thumbnail"));
                                        adData.setThumbnail(json.getString("thumbnail"));
                                        adData.setLink_mode(json.getInt("link_mode"));
                                        adData.setLink_id(json.getInt("link_id"));
                                        advertBeans.add(adData);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            mBinding.pager.setViewUrls(iamges,getActivity());
                            getTrip();

                        }
                    }
                });


    }

    private void getTrip() {
        OkGo.get(AppConfig.tlist)
                .tag(this)
                .params("city_id",BaseAppLication.getInstance().getCityid())
                .params("page",page)
                .params("size",4)
                .execute(new DialogCallback<Object>(getActivity()) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            List<TList.DataBean> dataBeans=new ArrayList<>();
                            try {
                                String data=GsonUtils.GsonString(response.body());
                                JSONObject json=new JSONObject(data);
                                Double total= json.getDouble("total");
                                int t = (new Double(total)).intValue();
                                mBinding.total.setText(t+"");
                                JSONArray array=json.getJSONArray("data");
                                if (array.length()>0){
                                    if(array.length()>=4){
                                        mBinding.pull.setCanLoadMore(true);
                                    }else {
                                        mBinding.pull.setCanLoadMore(false);
                                    }
                                    showData();
                                    for (int i=0;i<array.length();i++){
                                        JSONObject jsonObject=array.getJSONObject(i);
                                        TList.DataBean dataBean=new TList.DataBean();
                                        dataBean.setId(jsonObject.getInt("id"));
                                        dataBean.setDriver_avatar(jsonObject.getString("driver_avatar"));
                                        dataBean.setDriver_name(jsonObject.getString("driver_name"));
                                        dataBean.setDriver_id(jsonObject.getInt("driver_id"));
                                        dataBean.setHelp_count(jsonObject.getInt("help_count"));
                                        dataBean.setCar_no(jsonObject.getString("car_no"));
                                        dataBean.setDeparture_time(jsonObject.getString("departure_time"));
                                        dataBean.setSurplus(jsonObject.getInt("surplus"));
                                        dataBean.setPeople(jsonObject.getInt("people"));
                                        dataBean.setInitially(jsonObject.getString("initially"));
                                        dataBean.setWay(jsonObject.getString("way"));
                                        dataBean.setDestination(jsonObject.getString("destination"));
                                        dataBean.setIs_expired(jsonObject.getInt("is_expired"));
                                        dataBeans.add(dataBean);
                                    }
                                    dataBeanlist.addAll(dataBeans);
                                    adapter.setNewData(dataBeanlist);
                                }else {
                                    if (!CollectionUtils.isNullOrEmpty(dataBeanlist)){
                                        adapter.setNewData(dataBeanlist);
                                    }else {
                                        noData();
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showErrorView(response.code());
                    }
                });
    }


    //获取实名认证
    public void getname() {
        OkGo.<Realname>get(AppConfig.Getrealname)
                .tag(this)
                .execute(new NoDialogCallback<Realname>(getActivity()) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Realname> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())) {
                            BaseAppLication.getInstance().setIs_realname(response.body().getReview());
                            if (response.body().getReview() ==1){
                                mBinding.realname.setVisibility(View.GONE);
                                mBinding.ranliner.setVisibility(View.GONE);
                            }else {
                                mBinding.ranliner.setVisibility(View.VISIBLE);
                                mBinding.realname.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
    }


    //获取车主认证
    public void getRealname() {
        OkGo.get(AppConfig.Getmydriver)
                .tag(this)
                .execute(new NoDialogCallback<Object>(getActivity()) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            String data=GsonUtils.GsonString(response.body());
                            MyDriver myDriver= GsonUtils.GsonToBean(data,MyDriver.class);
                            if (myDriver.getReview()==1){
                                startActivityForResult(PushActivity.class,0,null,true);
                            }else {
                                type=1;
                                getmDialog("是否进入司机认证页面?","取消","确定").show();
                            }
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }



    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onResume() {
        super.onResume();
        if(isup) {
            if (isRequireCheck){
                if (mPermissionsChecker.judgePermissions(PERMISSIONS)) {
                    ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, PERMISSION_REQUEST_CODE);
                }
            }
        }else {
            isup = false;
        }
        if (!NotificationUtils.isNotificationEnabled(getActivity())){
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("关闭通知您将无法收到任何的通知信息,对您的使用会造成很大的困扰,强烈建议开启！！")
                    .setTopImage(R.mipmap.certification_prompt)
                    .setNegativeButton("残忍拒绝", (dialog2, which) -> mDialog.dismiss())
                    .setPositiveButton("开启通知", (dialog, which) -> {
                        dialog.dismiss();
                        NotificationUtils.toSetting(getActivity());
                    });
            mDialog = builder.create();
            mDialog.show();
        }
    }



    /**
     * 用户权限处理,
     * 如果全部获取, 则直接过.
     * 如果权限缺失, 则提示Dialog.
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {
        if (hasAllPermissionsGranted(grantResults)) {
            isRequireCheck = true;
            showPermissionDialog();
        } else {

            isRequireCheck = false;
        }
    }

    //判断含有全部的权限集
    private boolean hasAllPermissionsGranted( int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;

    }

    /**
     * 提示对话框
     */
    private void showPermissionDialog() {
        type=2;
        getmDialog("当前应用缺少必要权限。请点击\\\"设置\\\"-打开所需权限。","取消","设置").show();
    }

    @Override
    public void onOk() {
        if (type==1){
            startActivityForResult(CartCertificationActivity.class,0,null,true);
        }else {
            startAppSettings();
        }
    }


    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getActivity().getPackageName()));
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==96){
            if (!CollectionUtils.isNullOrEmpty(data)){
                city= data.getStringExtra("city");
                mBinding.site.setText(city);
                if (!BaseAppLication.getInstance().ispage()){
                    BaseAppLication.getInstance().setIspage(true);
                }
                loadData(true);
            }
        }
    }

}
